﻿using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;

using System.Diagnostics;

namespace Hont.AStar
{
    public class HontAStarUnityPathfindingDebuger : MonoBehaviour
    {
        public HontAStarUnity astar;
        public int count = 10;
        public float delay = 0.1f;
        public float debug_stopwatchMs = 0;

        Vector3[] mCachedPath;
        Position[] mCachePosition;

        WaitForSeconds mCacheWaitForSeconds;
        Stopwatch mStopwatch;


        void OnEnable()
        {
            if (astar == null) return;

            mStopwatch = new Stopwatch();
            mCacheWaitForSeconds = new WaitForSeconds(delay);

            mCachedPath = new Vector3[100];
            mCachePosition = new Position[100];

            StartCoroutine(EnumeratorUpdate());
        }

        IEnumerator EnumeratorUpdate()
        {
            yield return null;

            while (true)
            {
                for (int i = 0; i < count; i++)
                {
                    var aVector = default(Vector3);
                    var bVector = default(Vector3);

                    aVector.x = UnityEngine.Random.Range(astar.LocalBounds.min.x, astar.LocalBounds.max.x);
                    aVector.y = UnityEngine.Random.Range(astar.LocalBounds.min.y, astar.LocalBounds.max.y);
                    aVector.z = UnityEngine.Random.Range(astar.LocalBounds.min.z, astar.LocalBounds.max.z);

                    bVector.x = UnityEngine.Random.Range(astar.LocalBounds.min.x, astar.LocalBounds.max.x);
                    bVector.y = UnityEngine.Random.Range(astar.LocalBounds.min.y, astar.LocalBounds.max.y);
                    bVector.z = UnityEngine.Random.Range(astar.LocalBounds.min.z, astar.LocalBounds.max.z);

                    aVector = astar.transform.TransformPoint(aVector);
                    bVector = astar.transform.TransformPoint(bVector);

                    mStopwatch.Reset();
                    mStopwatch.Start();
                    var length = astar.StartPathfinding_NonAlloc(aVector, bVector, ref mCachePosition, ref mCachedPath);
                    mStopwatch.Stop();

                    debug_stopwatchMs = mStopwatch.ElapsedMilliseconds;

                    if (length > -1)
                    {
                        var tempList = new List<Vector3>();
                        for (int j = 0; j < length; j++)
                        {
                            tempList.Add(mCachedPath[j]);
                        }

                        HontAStarUnityHelper.DebugPathfindingPath(tempList.ToArray());
                    }
                }

                yield return mCacheWaitForSeconds;
            }
        }
    }
}
